package com.gz.controller;

import com.gz.dto.PaperQuestionDto;
import com.gz.dto.PaperUserDto;
import com.gz.dto.QuestionDto;
import com.gz.entity.*;
import com.gz.service.*;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import com.gz.vo.R;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import com.gz.dto.UserAnswersDto;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 用户答题结果详情表(UserAnswers)表控制层
 *
 * @author makejava
 * @since 2024-05-27 15:40:59
 */
@RestController
@RequestMapping("userAnswers")
@Api(value = "用户答题结果详情表控制层", tags = {"用户答题结果详情表控制层"})
public class UserAnswersController {
    @Value("${app.aiPaperQuestionCnt}")
    private String aiPaperQuestionCnt;
    @Value("${app.aiPaperTotalScore}")
    private String aiPaperTotalScore;
    /**
     * 答题表接口
     */
    @Autowired
    private UserAnswersService userAnswersService;
    /**
     * 答题卡接口
     */
    @Autowired
    private AnswersService answersService;
    /**
     * 试卷接口
     */
    @Autowired
    private TestPaperService testPaperService;
    /**
     * 试卷关联题目接口
     */
    @Autowired
    private PaperQuestionService paperQuestionService;
    /**
     * 试卷关联题目接口
     */
    @Autowired
    private PaperUserService paperUserService;
    /**
     * 题目接口
     */
    @Autowired
    private QuestionService questionService;

    /**
     * 分页查询
     *
     * @param dto 筛选条件
     * @return 查询结果
     */
    @ApiOperation(value = "分页查询")
    @PostMapping("/queryPage")
    public R queryByPage(@RequestBody UserAnswersDto dto, HttpServletRequest request) {
        return R.ok(userAnswersService.queryByPage(dto));
    }

    /**
     * 分页查询
     *
     * @param dto 筛选条件
     * @return 查询结果
     */
    @ApiOperation(value = "条件查询")
    @PostMapping("/queryAll")
    public R queryAll(@RequestBody UserAnswersDto dto, HttpServletRequest request) {
        return R.ok(userAnswersService.queryAll(dto));
    }

    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     */
    @ApiOperation(value = "主键查询")
    @GetMapping("/queryById")
    public R<UserAnswers> queryById(@RequestParam("id") Integer id) {
        return R.ok(userAnswersService.queryById(id));
    }

    /**
     * 新增数据
     *
     * @param userAnswers 实体
     * @return 新增结果
     */
    @ApiOperation(value = "新增数据")
    @PostMapping("/save")
    public R<UserAnswers> add(@RequestBody UserAnswers userAnswers) {
        return R.ok(userAnswersService.insert(userAnswers));
    }

    /**
     * 新增数据
     *
     * @param batchData 集合
     * @return 新增结果
     */
    @ApiOperation(value = "交卷")
    @PostMapping("/saveBatch")
    @Transactional
    public R<?> addBatch(@RequestBody List<UserAnswers> batchData) {
        if (CollectionUtils.isEmpty(batchData)) {
            return R.failure("不能交白卷");
        }
        Integer answerId = batchData.get(0).getAnswerId();
        Answers answers = answersService.queryById(answerId);
        PaperUser paperUser = new PaperUser();
        paperUser.setPaperId(answers.getExamId() + "");
        /** 更改已发卷状态变成提交状态 */
        paperUser.setStatus(2);
        /** 先查询该用户未交卷的最早的试卷用户关系表的id方便更改已答卷状态 */
        PaperUserDto puDto = new PaperUserDto();
        puDto.setPaperId(answers.getExamId() + "");
        if(null!=answers.getUserId()){
            puDto.setUserId(answers.getUserId()+"");
        }else{
            return R.failure("该用户不存在答题卡");
        }
        /** 同一张卷子发多次提交的话只改最早发的那次的 */
        puDto.setOrderField("crtDt");
        puDto.setOrderType("desc");
        puDto.setStatus(1);
        puDto.setPageNum(1);
        puDto.setPageSize(10);
        List<PaperUser> paperUsers = paperUserService.queryAll(puDto);
        if(CollectionUtils.isNotEmpty(paperUsers)){
        PaperUser papUser = new PaperUser();

            papUser =  paperUsers.get(0);
            paperUser.setId(papUser.getId());
            paperUser.setStatus(2);
            paperUserService.update(paperUser);
        }else{
            return R.failure("该用户不存在待答试卷");
        }
        Integer examId = answers.getExamId();
        TestPaper testPaper = testPaperService.queryById(examId);
        BigDecimal eachQtScore = null;
        BigDecimal rightScore = null;
        BigDecimal emptyScore = null;
        BigDecimal wrongScore = null;

        if (1 == testPaper.getPaperType() && (null == testPaper.getRightScore() || null == testPaper.getWrongScore())) {
            return R.failure("手动生成试卷，答对或答错或不答分值不能为空");
        }

        if (null != testPaper.getPaperType()) {
            /** 如果是手动生成试卷，那每题得分值由创建试卷时填的分值来计算 */
            if (1 == testPaper.getPaperType()) {
                rightScore = testPaper.getRightScore();
                emptyScore = testPaper.getEmptyScore();
                wrongScore = testPaper.getWrongScore();
            } else {
                /** 智能试卷是配置的题目总分除以配置的题目总数 */
                eachQtScore = new BigDecimal(aiPaperTotalScore).divide(new BigDecimal(aiPaperQuestionCnt)).setScale(2, BigDecimal.ROUND_HALF_UP);
            }
        } else {
            eachQtScore = new BigDecimal(0);
        }
        Map answerMap = new HashMap<>();
        /** 先拿到所有题目id集合 */
        List<Integer> qIdS = batchData.stream().map(a -> {
            return a.getQuestionId();
        }).collect(Collectors.toList());
        QuestionDto questionDto = new QuestionDto();
        questionDto.setIds(qIdS);
        List<Question> questions = questionService.queryAll(questionDto);
        for (Question question : questions) {
            answerMap.put(question.getId(), question.getQuestionAnswer());
        }
        for (UserAnswers a : batchData) {
            String answer = (String) answerMap.get(a.getQuestionId());
            a.setQuestionAnswer(answer);
            a.setSubmitTime(new Date());
            /** 如果是手动生成试卷，那每题得分值由创建试卷时填的分值来计算 */
            if (1 == testPaper.getPaperType()) {
                if (StringUtils.isEmpty(a.getUserAnswer())) {
                    a.setIsCorrect(2);
                    a.setGetScore(emptyScore);
                } else if (answer.equalsIgnoreCase(a.getUserAnswer().trim())) {
                    a.setIsCorrect(1);
                    a.setGetScore(rightScore);
                } else {
                    a.setIsCorrect(0);
                    a.setGetScore(wrongScore);
                }
            } else {
                /** 如果是ai试卷或者错题试卷，那每题得分值由总分除以固定题目数得来*/
                if (!StringUtils.isEmpty(a.getUserAnswer()) && answer.equalsIgnoreCase(a.getUserAnswer().trim())) {
                    a.setIsCorrect(1);
                    a.setGetScore(eachQtScore);
                } else {
                    a.setIsCorrect(0);
                    a.setGetScore(BigDecimal.ZERO);
                }
            }
        }
        return R.ok(userAnswersService.insertBatch(batchData));
    }

    /**
     * 编辑数据
     *
     * @param userAnswers 实体
     * @return 编辑结果
     */
    @ApiOperation(value = "编辑数据")
    @PostMapping("/update")
    public R<UserAnswers> edit(@RequestBody UserAnswers userAnswers) {
        return R.ok(userAnswersService.update(userAnswers));
    }

    /**
     * 删除数据
     *
     * @param id 主键
     * @return 删除是否成功
     */
    @GetMapping("/deleteById")
    @ApiOperation(value = "删除数据")
    public R<Boolean> deleteById(@RequestParam("id") Integer id) {
        return R.ok(userAnswersService.deleteById(id));
    }

}

